<template>
    <van-popup
        v-model:show="setat.open"
        :close-on-click-overlay="false"
        teleport="#app"
        style="background: transparent"
    >
        <van-form @submit="onSubmit">
            <div class="referrer-box">
                <van-icon name="cross" @click="cross" />
                <div class="title">
                    {{ $t("layout.Invitationcode") }}
                </div>
                <!-- <div class="label">
                    {{ $t("layout.Nodeinvitationcode") }}
                </div> -->
                <van-field
                    v-model="setat.referrer"
                    :placeholder="$t('layout.Pleaseenterinvitationcode')"
                ></van-field>
                <van-button
                    type="primary"
                    native-type="submit"
                    :loading="setat.loading"
                    >{{ $t("layout.activation") }}</van-button
                >
            </div>
        </van-form>
    </van-popup>
</template>
<script lang="ts">
import { defineComponent, onMounted, nextTick, watch, reactive } from "vue";
import { showToast } from "vant";
import { UserModule } from "@/store/modules/user";
import { versig, verifyToken, isUserExist } from "@/api/nodeapi";
import { Set_App_Token_Key2, Get_App_Token_Key2 } from "@/utils/auth";
import { FormatDate } from "@/utils/formatDate";
import { useRouter } from "vue-router";

export default defineComponent({
    emits: ["load", "cross"],
    setup(props, ctx) {
        const router = useRouter();
        const setat: any = reactive({
            open: false,
            loading: false,
            referrer: router.currentRoute.value.query.referrer || "",
        });
        const onSubmit = () => {
            if (setat.referrer) {
                sendRegister();
            }
        };
        const sendRegister = async (mes, loadBool): Promise<void> => {
            try {
                const message =
                    mes ||
                    "welcome to login at " +
                        FormatDate(new Date(), "yyyy-MM-dd hh:mm:ss") +
                        " bind " +
                        setat.referrer;
                const sign = await tronWeb.trx.signMessageV2(message);
                const res = await versig({
                    message: message,
                    signature: sign,
                });
                if (res.data.code == 20) {
                    const key = {
                        ...Get_App_Token_Key2(),
                        [UserModule.userAddr]: res.data.data.Token,
                    };
                    Set_App_Token_Key2(key);
                    const userAddr = UserModule.userAddr;
                    UserModule.SET_USERADDR("");
                    await nextTick(() => {
                        UserModule.SET_USERADDR(userAddr as string);
                        setat.open = false;
                        if (!loadBool) {
                            ctx.emit("load", { isloadData: true });
                        }
                    });
                } else {
                    showToast(res.data.message);
                }
            } catch (error: any) {
                console.log(error);
                showToast(error);
            }
        };
        const loadVerifyToken = (bool = false) => {
            return new Promise((resolve, reject) => {
                setat.open = false;
                verifyToken().then(async (res) => {
                    if (res.data.code != 20) {
                        isUserExist({ address: UserModule.userAddr }).then(
                            async (res) => {
                                if (res.data.code == 20) {
                                    const message =
                                        "welcome to login at " +
                                        FormatDate(
                                            new Date(),
                                            "yyyy-MM-dd hh:mm:ss"
                                        );
                                    await sendRegister(message, true);
                                    resolve(res);
                                } else {
                                    if (bool) {
                                        setat.open = true;
                                    }
                                    setat.open = true;
                                }
                            }
                        );
                    } else {
                        setat.open = false;
                        resolve(res);
                    }
                });
            });
        };
        const cross = () => {
            setat.open = false;
            ctx.emit("cross");
        };
        onMounted(async () => {});
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadVerifyToken();
                }
            },
            { immediate: true }
        );
        return {
            UserModule,
            setat,
            sendRegister,
            onSubmit,
            loadVerifyToken,
            cross,
        };
    },
});
</script>
<style lang="less" scoped>
.referrer-box {
    position: relative;
    padding: 32px;
    box-sizing: border-box;
    border-radius: 20px;
    background: #fff;
    width: 448px;
    max-width: 448px;

    .van-icon {
        position: absolute;
        right: 32px;
        top: 39px;
        font-size: 24px;
        cursor: pointer;
    }

    .title {
        color: #000;
        font-size: 24px;
        font-weight: 600;
        line-height: 160%; /* 38.4px */
    }
    .label {
        margin-top: 30px;
        color: #000;
        font-size: 16px;
        font-weight: 400;
        line-height: 120%; /* 19.2px */
    }

    .van-field {
        margin-top: 8px;
        width: 100%;
        padding: 0;
        &::after {
            display: none;
        }

        &:deep(.van-cell__value) {
            .van-field__control {
                height: 46px;
                padding: 0 15px;
                font-size: 15px;
                border-radius: 10px;
                border: 1px solid #d9d9d9;
                box-sizing: content-box;
                &:focus {
                    border: 1px solid #eb0029;
                    background: #fff7f7;
                }
            }
        }
    }

    .van-button {
        height: 45px;
        margin-top: 20px;
    }
    @media (max-width: 1000px) {
        & {
            width: 90vw;
            .van-field {
                &:deep(.van-cell__value) {
                    .van-field__control {
                        font-size: 14px;
                    }
                }
            }
        }
    }
}
</style>
